let mongoose = require('mongoose');
let schema = new mongoose.Schema({
    missions:{
        type:[require('./gameUser.mission.item')],
        default:[]
    },
    lastRefreshTick:{
        type:Number,
        default:0
    }
},{versionKey:false});

let config={
    //1:{sort:1,group:0,title:'每日签到奖励',description:'领取每日签到奖励',maxProcess:1,rewards:[{type:1,count:10},{type:2,count:10}]},
    // 2:{sort:2,title:'邀请好友',description:'邀请一个新的好友进入游戏',maxProcess:1,rewards:[{type:1,count:100},{type:2,count:50}]},
    3:{sort:3,group:0,title:'连赢奖励',description:'当日连赢3局获得奖励',maxProcess:3,rewards:[{type:2,count:200}]},
    4:{sort:4,group:0,title:'好友对抗奖励',description:'参与好友对抗1局',maxProcess:1,rewards:[{type:2,count:50}]},
    5:{sort:5,group:0,title:'随机乱斗奖励',description:'参与随机乱斗10局',maxProcess:10,rewards:[{type:2,count:100}]},
    6:{sort:6,group:0,title:'早自习奖励',description:'每天早上6:00-8:00玩满2局',maxProcess:2,rewards:[{type:2,count:100}]},
    7:{sort:7,group:0,title:'晚自习奖励',description:'每天晚上10:00-12:00玩满2局',maxProcess:2,rewards:[{type:2,count:100}]},
    101:{sort:1,group:1,title:'段位奖励',description:`段位提升到《{0}》，领取奖励`,maxRound:23,stepProcess:1,stepRewards:[{type:2,count:30}]},
    202:{sort:1,group:2,title:'互助奖励',description:`通过分享邀请老玩家进入游戏`,maxProcess:1,rewards:[{type:2,count:50}]},
    203:{sort:2,group:2,title:'邀请奖励',description:`邀请激活1个新玩家进入游戏`,maxProcess:1,rewards:[{type:2,count:500}]}
};

schema.methods = {
    //返回轮询数据
    poll(){
        let completedMissions=this.missions.filter(item=>{return item.status===1;}).length;
        return completedMissions;
    },
    //登陆自动运行
    loginAutoRun(){
        this._refresh();
    },
    getMissions(options){
        this._refresh();
        let result=[];
        this.missions.forEach(item=>{
            let obj={};
            Object.assign(obj,JSON.parse(JSON.stringify(item)),{title:config[item.type].title,description:config[item.type].description});
            if(obj.group===0||obj.group===2){
                obj.rewards=config[item.type].rewards;
            }
            if(obj.group===1){
                obj.rewards=this._getGrowUpRewards(item);
                if(obj.type===101){
                    let levelDescriptions=options.self.ppt.getLevelDescriptions();
                    obj.description=obj.description.replace('{0}',levelDescriptions[item.currentRound+1].levelName);
                }else{
                    //obj.description=obj.description.replace('{0}',config[item.type].stepProcess*(item.currentRound+1));
                }
            }
            result.push(obj);
        });
        result.sort((a,b)=>{
           return a.status==b.status?a.sort-b.sort:b.status-a.status;
        });
        return result;
    },
    _refresh(){
        //移除不在上面的任务
        this.missions.forEach(mission=>{
            if(!config[mission.type]){
                let index=this.missions.findIndex(item=>{return item.type=mission.type;});
                if(index>=0){
                    this.missions.splice(index,1);
                }
            }
        });
        //创建没有的任务
        let keys=Object.keys(config);
        for(let i=0;i<keys.length;i++){
            let missionConfig=config[keys[i]];
            let mission=this.missions.find(item=>{return item.type==keys[i]});
            if(!mission){
                switch(missionConfig.group){
                    case 0:{
                        mission={type:keys[i],maxProcess:missionConfig.maxProcess};
                        break;
                    }
                    case 1:{
                        mission={
                            type:keys[i],
                            group:1,
                            maxProcess:missionConfig.stepProcess,
                        };
                        break;
                    }
                    case 2:{
                        mission={
                            type:keys[i],
                            group:2,
                            maxProcess:missionConfig.maxProcess,
                        };
                        break;
                    }
                }
                this.missions.push(mission);
            }
        }
        //如果上次刷新时间在前一天，则刷新当天的日常任务
        let time=new Date(this.lastRefreshTick);
        let now=new Date();
        if(time.toLocaleDateString()!==now.toLocaleDateString()){
            this.missions.forEach(item=>{
                if(item.group===0){
                    item.status=0;
                    item.process=0;
                    item.maxProcess=config[item.type].maxProcess;
                }
                item.data=[];
            });
            this.lastRefreshTick=new Date().getTime();
        }
    },
    //重置单个任务 用于连赢奖励
    resetOneMission(type){
        let mission=this.missions.find(item=>{return item.type===type});
        if(!!mission&&mission.status===0){
            mission.process=0;
        }
    },
    //完成一次日常任务进度
    doOneMission(type){
        let mission=this.missions.find(item=>{return item.type===type});
        if(!!mission&&mission.status===0){
            mission.process+=1;
            if(mission.process>=mission.maxProcess){
                mission.status=1;
            }
            return true;
        }
        return false;
    },
    //完成互助任务
    async doHelpMission(options){
        let GameUserModel=mongoose.models['GameUser'];
        if(!options.parentId){
            return;
        }
        let parentUser=await GameUserModel.findById(options.parentId);
        if(!!parentUser){
            let mission=parentUser.mission.missions.find(item=>{return item.type===202});
            let userId=options.self._id.toString();
            if(!!mission&&mission.data.indexOf(userId)<0&&userId!==options.parentId){
                mission.data=[].concat(mission.data,[userId]);
                parentUser.mission.doOneMission(202);
                await parentUser.save();
            }
        }
    },
    //完成累积邀请任务
    async doInviteMission(gameUser){
        let userId=gameUser._id.toString();
        let mission=this.missions.find(item=>{return item.type===203});
        if(!!mission&&mission.data.indexOf(userId)<0){
            mission.data=[].concat(mission.data,[userId]);
            this.doOneMission(203);
        }
    },
    //获取成长任务当前轮的奖励
    _getGrowUpRewards(mission){
        let rewards=[].concat(config[mission.type].stepRewards);
        let result=[];
        for(let i=0;i<rewards.length;i++){
            result.push({
                type:rewards[i].type,
                count:rewards[i].count*(mission.currentRound+1)
            });
        }
        return result;
    },
    //拷贝一份奖励，避免污染对象
    _copyRewards(rewards){
        let result=[];
        rewards.forEach(reward=>{
            result.push({
                type:reward.type,
                count:reward.count
            })
        });
        return result;
    },
    //领取奖励
    receive(options){
        return this._receive(options.self,options.type,1);
    },
    //双倍领取
    receiveDouble(options){
        return this._receive(options.self,options.type,2);
    },
    _receive(gameUser,type,multiple=1){
        let mission=this.missions.find(item=>{return item.type==type});
        if(!!mission&&mission.status===1){
            let rewards=[];
            switch(mission.group){
                case 0:{
                    //如果是日常任务，则正常领取
                    rewards=this._copyRewards(config[mission.type].rewards);
                    break;
                }
                case 1:{
                    //如果是成长任务，则根据再第几环领取
                    rewards=this._getGrowUpRewards(mission);
                    break;
                }
                case 2:{
                    rewards=this._copyRewards(config[mission.type].rewards);
                    break;
                }
            }
            //将奖励乘以倍数
            for(let i=0;i<rewards.length;i++){
                rewards[i].count*=multiple;
            }
            gameUser.getGoods(rewards);
            //领取完毕，判断是永久完成任务还是开始下一轮任务
            switch(mission.group){
                case 0:{
                    mission.status=-1;
                    break;
                }
                case 1:{
                    mission.currentRound+=1;
                    if(mission.currentRound>=config[mission.type].maxRound){
                        mission.status=-1;
                    }else{
                        mission.maxProcess=config[mission.type].stepProcess*(mission.currentRound+1);
                        mission.status=0;
                    }
                    //如果是段位任务，判断是否已经完成下一把任务
                    let nextMethod='next'+mission.type;
                    if(!!this[nextMethod]){
                        this[nextMethod](gameUser);
                    }
                    break;
                }
                case 2:{
                    mission.maxProcess+=1;
                    mission.status=0;
                    let nextMethod='next'+mission.type;
                    if(!!this[nextMethod]){
                        this[nextMethod](gameUser,mission);
                    }
                    break;
                }
            }
            return rewards;
        }
        return [];
    },
    next101(gameUser){
        gameUser.ppt.levelUp(gameUser,0);
    },
    next202(gameUser,mission){
        if(mission.maxProcess==mission.data.length){
            mission.process=mission.maxProcess;
            mission.status=1;
        }
    },
    next203(gameUser,mission){
        if(mission.maxProcess==mission.data.length){
            mission.process=mission.maxProcess;
            mission.status=1;
        }
    },
};

module.exports = schema;